<template>
  <v-container class="logsManagement-container " fluid>
    <v-row>
      <v-col cols="12">
        <v-card elevation="10" class="pa-4">
          <v-card-title class="d-flex justify-space-between">
            <div>
              <v-btn v-if="perms('dev_generator_insert')" color="primary" prepend-icon="mdi-plus" class="mr-2"
                @click="handleInsert">添加</v-btn>
              <v-btn v-if="perms('dev_generator_import')" color="primary" prepend-icon="mdi-database-import"
                class="mr-2" @click="handleImport">从数据库导入</v-btn>
              <v-btn v-if="perms('dev_generator_delete')" color="error" prepend-icon="mdi-delete" class="mr-2"
                :disabled="!selectRows.length" @click="handleDelete">批量删除</v-btn>
              <v-btn v-if="perms('dev_generator_create')" color="warning" prepend-icon="mdi-code-braces" class="mr-2"
                :disabled="selectRows.length !== 1" @click="handleCreate">生成代码</v-btn>
              <v-btn v-if="perms('dev_generator_createMenu')" color="warning" prepend-icon="mdi-menu" class="mr-2"
                :disabled="selectRows.length !== 1" @click="showMenuChoose">生成菜单</v-btn>

            </div>
            <div class="d-flex align-center gap-2">
              <!-- 输入框优化 -->
              <v-text-field v-model="queryForm.tableName_LIKE" style="width: 200px;" label="请输入名称" density="compact"
                hide-details />
              <v-btn color="primary" prepend-icon="mdi-magnify" variant="flat" class="h-100" @click="queryData">
                查询
              </v-btn>
            </div>



          </v-card-title>
          <v-card-text>
            <v-form @submit.prevent="queryData">
              <v-row>
                <v-col cols="4">
                </v-col>
                <v-col cols="2">
                </v-col>
              </v-row>
            </v-form>
            <v-data-table :loading="listLoading" :items="list" :headers="headers" show-select v-model="selectRows"
              class="mt-4" :page="queryForm.pageNo" :items-per-page="queryForm.pageSize" :server-items-length="total"
              @update:page="handleCurrentChange" @update:items-per-page="handleSizeChange">
              <template v-slot:item.index="{ index }">
                {{ (queryForm.pageNo - 1) * queryForm.pageSize + index + 1 }}
              </template>
              <template v-slot:item.tableType="{ item }">
                <span>{{ getDictNameByValue('table_type', item.tableType) }}</span>
              </template>
              <template v-slot:item.jdbcType="{ item }">
                <span>{{ getDictNameByValue('jdbc_type', item.jdbcType) }}</span>
              </template>
              <template v-slot:item.izSync="{ item }">
                <v-chip :color="item.izSync === '1' ? 'success' : 'info'" small>{{ getDictNameByValue('no_yes',
                  item.izSync) }}</v-chip>
              </template>
              <template v-slot:item.actions="{ item }">
                <v-btn v-if="perms('dev_generator_update')" variant="text" @click="handleUpdate(item)">编辑</v-btn>
                <v-divider vertical></v-divider>
                <v-menu>
                  <template #activator="{ props }">
                    <v-btn v-bind="props" variant="text">更多<v-icon end>mdi-chevron-down</v-icon></v-btn>
                  </template>
                  <v-list>
                    <v-list-item v-if="perms('dev_generator_sync')" @click="handleSync(item)">同步</v-list-item>
                    <v-list-item v-if="perms('dev_generator_delete')" @click="handleDelete(item)">删除</v-list-item>
                  </v-list>
                </v-menu>
              </template>
            </v-data-table>
            <v-pagination v-model="queryForm.pageNo" :length="Math.ceil(total / queryForm.pageSize)" :total-visible="7"
              @input="handleCurrentChange" class="mt-4" />
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
    <Edit ref="editRef" @fetchData="fetchData" />
    <ShowDatabaseTables ref="showDatabaseTablesRef" @fetchData="fetchData" />
    <GenCreate ref="genCreateRef" />
    <MenuManagementChoose ref="menuManagementChooseRef" @menuChoose="handleCreateMenu" />
  </v-container>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import Edit from './components/edit/TableEdit.vue';
import ShowDatabaseTables from './components/showDatabaseTables.vue';
import GenCreate from './components/GenCreate.vue';
import MenuManagementChoose from '@/components/opsli/menu/MenuManagementChoose.vue';
import { getList, doDelete, doDeleteAll, doSync, doCreateMenu } from '@/api/generator/tableManagement';
import { isNull } from '@/utils/validate';
import { useMessage } from '@/composables/useMessage';
const { success: showSuccess, error: showError } = useMessage();

const list = ref<any[]>([]);
const listLoading = ref(true);
const total = ref(0);
const selectRows = ref<any[]>([]);
const queryForm = reactive({
  pageNo: 1,
  pageSize: 10,
  tableName_LIKE: '',
});

const headers = [
  { title: '序号', key: 'index', width: 95 },
  { title: '表名称', key: 'tableName', width: 300 },
  { title: '表类型', key: 'tableType' },
  { title: '描述', key: 'comments' },
  { title: '数据库类型', key: 'jdbcType' },
  { title: '是否同步', key: 'izSync' },
  { title: '备注', key: 'remark' },
  { title: '操作', key: 'actions', sortable: false, width: 200 },
];

function perms(key: string) {
  // 权限判断函数，需根据实际项目实现
  return true;
}
function getDictNameByValue(type: string, value: string) {
  // 字典转换函数，需根据实际项目实现
  return value;
}
function handleInsert() {
  (editRef.value as any)?.showEdit();
}
function handleUpdate(row: any) {
  (editRef.value as any)?.showEdit(row);
}
function handleImport() {
  (showDatabaseTablesRef.value as any)?.show();
}
function handleCreate() {
  console.log('selectRows type:', typeof selectRows.value[0]);
  if (selectRows.value.length !== 1) return;

  // 如果selectRows是ID数组，需要从list中找到对应的对象
  const selectedId = selectRows.value[0];
  const selectedItem = list.value.find(item => item.id === selectedId);

  if (selectedItem) {
    console.log('selectRows:', selectedItem);

    (genCreateRef.value as any)?.showEdit(selectedItem);
  }
}
function showMenuChoose() {
  if (selectRows.value.length !== 1) return;

  (menuManagementChooseRef.value as any)?.showMenuChoose();
}
async function handleCreateMenu(menuNode: any) {
  if (isNull(menuNode)) return;

  // 如果selectRows已经是ID数组，直接使用
  const ids = selectRows.value;
  if (!ids.length) return;
  const tableId = ids[0];
  let { code, msg } = await doCreateMenu({ menuParentId: menuNode.id, tableId });
  if (code === 0) {
    showSuccess('添加成功');
  } else {
    showError(msg);
  }

}
async function handleDelete(row?: any) {
  if (row && row.id) {
    await doDelete({ id: row.id });
    fetchData();
  } else if (selectRows.value.length > 0) {
    // 如果selectRows已经是ID数组，直接使用
    const ids = selectRows.value;
    await doDeleteAll({ ids: ids as any });
    fetchData();
    selectRows.value = []; // 清空选择
  }
}
async function handleSync(row: any) {
  if (row.id) {
    await doSync({ id: row.id });
    fetchData();
  }
}
function handleSizeChange(val: number) {
  queryForm.pageSize = val;
  fetchData();
}
function handleCurrentChange(val: number) {
  queryForm.pageNo = val;
  fetchData();
}
function queryData() {
  queryForm.pageNo = 1;
  fetchData();
}
async function fetchData() {
  listLoading.value = true;
  const { data } = await getList(queryForm);
  if (!isNull(data)) {
    list.value = data.rows;
    total.value = data.total;
  }
  setTimeout(() => {
    listLoading.value = false;
  }, 300);
}

const editRef = ref();
const showDatabaseTablesRef = ref();
const genCreateRef = ref();
const menuManagementChooseRef = ref();

// 监听选择变化 - 用于调试
watch(selectRows, (newVal) => {
  console.log('选择变化:', newVal);
  console.log('选择数量:', newVal.length);
  if (newVal.length > 0) {
    console.log('第一个选中项的类型:', typeof newVal[0]);
    console.log('第一个选中项的值:', newVal[0]);
    console.log('是否为数字(索引):', typeof newVal[0] === 'number');
    console.log('是否为对象(行数据):', typeof newVal[0] === 'object');
  }
}, { deep: true });

fetchData();
</script>

<style scoped>
.logsManagement-container {
  /* padding: 24px; */
}
</style>
